<template>
  <div>
    <div class="user-info-box">
      <img class="user-img" src="../../assets/user_default.jpg">
      <div class="user-info" @click="detailDialog = true">
        <div class="user-name">
          {{ userTitle.nickname }}
          <svg class="icon" aria-hidden="true"><use xlink:href="#icon-bianji"></use></svg>
        </div>
        <div class="user-id">账号: {{ userTitle.username }}</div>
      </div>
    </div>
    <div class="user-options-box">
      <div class="options" v-for="opt in optionMenu" @click="opt.targetEvent">
        <svg class="icon" aria-hidden="true"><use :xlink:href="opt.iconName"></use></svg>
        <span>{{ opt.optName }}</span>
        <div class="icon-to">
          <svg class="icon" aria-hidden="true"><use xlink:href="#icon-you1"></use></svg>
        </div>
      </div>
    </div>

    <Dialog
      title="关于应用" 
      @close-dialog="aboutDialog = false;" 
      :visible="aboutDialog"
      :mask-btn="true"
      :width="320"
    >
      <div class="about-list-item"><span>软件名称:</span> iAccount个人记账软件</div>
      <div class="about-list-item"><span>当前版本:</span> {{ version }}</div>
      <div class="about-list-item"><span>前端开发:</span> 朱益杰</div>
      <div class="about-list-item"><span>后端开发:</span> 朱宇杰</div>
      <div class="about-list-item"><span>小组成员:</span> 竹天宏 朱益杰 朱宇杰 汪正毅 金垚 陈卓亚</div>
    </Dialog>

    <Dialog
      title="个人信息修改"
      @close-dialog="detailDialog = false;" 
      :visible="detailDialog"
      :maskBtn="true"
      :width="300"
      :button-list="btnList"
    >
      <el-form
        ref="changeFormRef"
        class="form-box"
        :rules="rules_change"
        :model="changeForm"
        label-position="right"
        label-width="auto"
        size="large"
      >
        <el-form-item label="用户名(账号)" prop="username">
          <el-input v-model="changeForm.username" clearable size="default" disabled />
        </el-form-item>
        <el-form-item label="昵称" prop="nickname">
          <el-input v-model="changeForm.nickname" clearable size="default" />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="changeForm.email" clearable size="default" />
        </el-form-item>
      </el-form>
    </Dialog>
  </div>
</template>

<script setup>
  import { ref, reactive, onMounted } from 'vue';
  import { useUserStore } from '@/stores/user';
  import { useRouter } from 'vue-router';
  import message from '@/utils/message';
  import Dialog from '@/components/Dialog.vue';
  import { getUserInfo, changeUserInfo } from '@/utils/api';

  const version = import.meta.env.VITE_VERSION;
  const useUser = useUserStore();
  const router = useRouter();
  let aboutDialog = ref(false);

  const getUserObj = () => {
    getUserInfo(useUser.userID)
      .then(res => {
        if(res.data.msg === '成功') {
          changeForm.uid = useUser.userID;
          changeForm.username = res.data.data.account;
          changeForm.nickname = res.data.data.name;
          changeForm.email = res.data.data.mailbox;
          userTitle.username = res.data.data.account;
          userTitle.nickname = res.data.data.name;
        } else {
          message.warning('获取用户信息失败');
        }
      })
      .catch(err => {
        message.warning('获取用户信息失败');
        console.warn(err);
      });
  };

  const optionMenu = [
    {
      optName: "设置",
      iconName: "#icon-shezhi",
      targetEvent: () => {
        router.push("/p/settings");
      }
    },
    {
      optName: "家庭成员管理",
      iconName: "#icon-jiaren",
      targetEvent: () => {
        router.push("/p/family");
      }
    },
    {
      optName: "关于应用",
      iconName: "#icon-bangzhu",
      targetEvent: () => {
        aboutDialog.value = true;
      }
    },
    {
      optName: "退出登录",
      iconName: "#icon-quxiao",
      targetEvent: () => {
        message.confirm('确认退出当前账号？', '退出登录', 'warning', () => {
          useUser.exitLogin();
          router.replace("/login");
        });
      }
    }
  ];

  let detailDialog = ref(false);
  const btnList = [
    {
      type: 'default',
      name: '取消',
      btnEvent: () => {
        detailDialog.value = false;
        changeForm.nickname = userTitle.nickname;
      },
      dis: false
    },
    {
      type: 'primary',
      name: '提交',
      btnEvent: () => {
        changeFormRef.value.validate((valid) => {
          if(valid) {
            changeUserInfo(changeForm)
              .then(res => {
                if(res.data) {
                  message.success('修改成功');
                  detailDialog.value = false;
                  getUserObj();
                }
              })
              .catch(err => {
                message.warning('修改失败，请重试');
                console.warn(err);
              });
          }
        });
      },
      dis: false
    }
  ];

  let changeFormRef = ref();
  let userTitle = reactive({
    username: "loading...",
    nickname: "loading...",
  });
  let changeForm = reactive({
    uid: "loading...",
    username: "loading...",
    nickname: "loading...",
    email: "loading...",
  });
  const validateUname = (rule, value, callback) => {
    if(value === '')
      callback(new Error('用户名不能为空！'));
    else if(value.length < 5)
      callback(new Error('用户名需大于5位！'));
    else
      callback();
  };
  const validateNickName = (rule, value, callback) => {
    if(value === '')
      callback(new Error('昵称不能为空！'));
    else if(value.length < 4)
      callback(new Error('昵称需大于4位！'));
    else
      callback();
  };
  const validateEmail = (rule, value, callback) => {
    if(value === '')
      callback(new Error('邮箱不能为空！'));
    else if(!(/^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/).test(value))
      callback(new Error('邮箱格式有误！'));
    else
      callback();
  };
  const rules_change = reactive({
    username: [{ validator: validateUname, trigger: 'blur' }],
    nickname: [{ validator: validateNickName, trigger: 'blur' }],
    email: [{ validator: validateEmail, trigger: 'blur' }],
  });

  onMounted(() => {
    getUserObj();
  });
</script>

<style lang="scss" scoped>
  .user-info-box{
    height: 90px;
    width: 90%;
    margin: auto;
    margin-top: calc(50px + 15px);
    display: flex;
    align-items: center;
    .user-img{
      width: 70px;
      height: 70px;
      border-radius: 5px;
      border: 1px solid $theme-shadow0;
    }
    .user-info{
      flex: 1;
      margin-left: 20px;
      cursor: pointer;
      .user-name{
        font-size: 16px;
        margin-bottom: 7px;
        color: $theme-main-dark;
        svg{
          margin-left: 10px;
        }
      }
      .user-id{
        font-size: 14px;
        color: $theme-shadow;
      }
    }
    .user-info:hover .user-name{
      color: $theme-main;
    }
  }
  .user-options-box{
    width: 85%;
    margin: auto;
    margin-top: 30px;
    .options{
      width: 100%;
      line-height: 55px;
      border-top: 1px solid $theme-shadow00;
      color: black;
      font-size: 15px;
      position: relative;
      cursor: pointer;
      span{
        margin-left: 15px;
      }
      .icon-to{
        position: absolute;
        right: 15px;
        top: 0;
        line-height: 55px;
        width: fit-content;
      }
    }
    .options:hover{
      background-color: $theme-shadow00;
    }
  }
  .about-list-item{
    line-height: 30px;
    span{
      font-weight: 600;
    }
  }
</style>